package main

import (
	"log"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

type Product struct {
	gorm.Model
	Name string
	Code  string
	Price int
}

func main() {

	//连接数据库
	//db, err := gorm.Open("sqlite3", ":memory:")
	db, err := gorm.Open("sqlite3", "demo.db")
	if err != nil {
		log.Fatal(err)
	}

	//创建数据表
	db.AutoMigrate(&Product{})

	//创建
	db.Create(&Product{Code: "L1212", Price: 1000})
	product := &Product{Code: "L1212", Price: 1200}
	db.Save(&product) //如果主健有值则更新，否则创建

	//读取
	var p Product
	db.First(&p, 1)
	db.First(&p, "code=?", "L1212")

	//更新
	db.Model(&p).Update("Price", 2000)
	db.Updates(&p) //只更新非零值字段
	p.Code = "S1212"
	p.Price = 240
	db.Select("Code", "Price").Updates(&p)  //只更新Code Price
	db.Omit("Code").Updates(&p)             //除code外的全部字段更新
	db.Select("*").Omit("Code").Updates(&p) //除code外的全部字段
	db.Select("Price").Updates(map[string]interface{"Price":200,"Name":"T-Shit"})

	db.Delete(&product)
}
